<?php
/**
 * Created by PhpStorm.
 * User: ysfl
 * Date: 2015/11/29
 * Time: 20:55
 * 流水帐模块
 */

namespace modules\admin;

use Cross\MVC\Module;

class WastebookModule extends Module
{

    /**
     * 流水表
     *
     * @var string
     */
    protected $tables = 'xrk_wastebook';

    /**
     * 库存表
     */
    protected $itables = "xrk_inventory";

    /**
     * 出库表
     */
    protected $otables = "xrk_inventory_o";

    /**
     * 支出表
     */
    protected $tables_Expenditure = "xrk_expenditure";

    /**
     * 添加流水
     *
     * @param $data
     * @return text
     */
    function addWastebook($data)
    {

        //获取商品数据
        $item_info = $this->link->get($this->itables,'*',array('i_name' => $data['item']));

        //获得商品类型
        $data['type'] = $item_info['type'];

        //检查表单是否为空
        foreach ($data as $key => & $val) {

            if ($val == "") {

                switch($key)
                {
                    case 'item':
                        $name = "商品名称";
                        break;

                    case 'mprice':
                        $name = "付款方式";
                        break;

                    case 'price':
                        $name = "价格";
                        break;

                    case 'addr':
                        $name = "店名";
                        break;

                    case 'name':
                        $name = "操作员";
                        break;

                    default:
                        $name = $key;
                        break;
                }

                if ($data['del_rewards'] == 0  && $data['v_id'] != ""){

                    $data['add_rewards'] = $data['price'];

                }

                if ($data['name'] == ""){

                    $data['name'] = $_SESSION['uname'];

                }

                //排除列表
                if (
                    $key != "del_rewards" &&
                    $key != "text"
                ){

                    return '<div class="alert alert-danger" role="alert">请输入：<b style="color: #FFEA44;">'.$name.'</b></div>';

                    unset($data[$key]);
                }
            }
        }

        //防止时间为0
        $chek_date = strtotime($data['time']) ? strtotime($data['time']) : false;

        if($chek_date === false){

            $time = date("Y-m-d H:i:s");

        }
        else{

            $time = $data['time'];

        }


        //筛选分店编码,方便以后添加分店
        switch($data['addr'])
        {
            /*
                $addr:店面字段名
                $a_id:店面编号
            */
            case "文化广场店":
                $addr = "wh";
                $a_id = '1';
                break;

            case "白露店":
                $addr = "bl";
                $a_id = '2';
                break;
        }

        $item_type = $item_info['type'] != "服务费" ? 0 : 1;

        //库存是否有货，服务费不计算库存数量
        if (!$item_type && $item_info[$addr] <= 0){
            return '<div class="alert alert-danger" role="alert">这个商品库存已经为0！请联系管理员确认库存！</div>';
        }

        //计算需要扣除的库存数量
        $s = $item_type ? 0 : $item_info[$addr] - $data['num'];

        //计算订单编号,规则：店铺编号+用户编号+年+月+日+时+分+秒+2位随机数
        $id = $a_id.$_SESSION['uid'].date('ymdHis').rand(10,99);

        //执行扣除当前店面库存
        $inventory = $this->link->update($this->itables,array($addr => $s),array('i_name' => $data['item']));

        //组装销售数据
        $inventory_o = $this->link->add($this->otables,array(

            //订单编号
            'entry' => $id,

            //订单时间
            'time' => $time,

            //商品名字
            'i_name' => $data['item'],

            //商品编号
            'i_id' => $item_info['id'],

            //商品价格
            'price' => $data['price'],

            //销售店面名字
            $addr => $data['num'],

            //销售员
            'o_name' => $data['name'],

            //订单备注
            'info' => $data['text']
        ));

        //组装流水数据
        $waste = $this->link->add($this->tables,array(

            //订单编号
            'entry' => $id,

            //会员号
            'v_id' => $data['v_id'],

            //公司客户名字
            'g_id' => $data['g_id'],

            //获得积分
            'add_rewards' => $data['add_rewards'],

            //消费积分
            'del_rewards' => $data['del_rewards'],

            //销售店面名字
            'addr' => $data['addr'],

            //订单时间
            'time' => $time,

            //商品名字
            'item' => $data['item'],

            //商品类型
            'type' => $data['type'],

            //商品数量
            'num' => $data['num'],

            //商品价格
            'price' => $data['price'],

            //商品成本
            'cost' => $item_info['cost'] * $data['num'],

            //付款方式 现金/未付
            'mprice' => $data['mprice'],

            //销售员名字
            'name' => $data['name'],

            //订单状态 默认0(没有入账)
            'start' => 0,

            //订单备注
            'info' => $data['text']
        ));

        //数据写入数据库
        if ($inventory && $inventory_o && $waste){
            return '<div class="alert alert-success" role="alert"><b style="color:red">'.$data['item'].'</b> 添加成功！</div>';
        }
        else{
            return '<div class="alert alert-danger" role="alert">添加失败，请联系管理员</div>';
        }

    }

    /**
     * 查询价格
     */
    function Q_Price($data)
    {
        $user = $data['user'];

        switch ($user)
        {
            case "oc":

                $price = "r_price";

                break;

            case "ec":

                $price = "v_price";

                break;

            case "vip":

                $price = "v_price";

                break;
        }

        //查询价格
        $s = $this->link->get($this->itables,$price,array('i_name' => $data['iname']));

        //返回价格实例
        return $s[$price];
    }

    /**
     * 查询流水
     * @return array
     */
    function Query_Wastebook_List($data)
    {
        //查询并返回结果
        return $this->link->select('*')
            ->from($this->tables)
            ->where($data)
            ->orderBy(array('time desc'))
            ->stmt()
            ->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * 计算金额
     * @return array
     */
    function C_Money($data)
    {

        $c = $this->link->select( 'SUM(price)')
            ->from($this->tables)
            ->where($data)
            #->getSQL();print_r($c);exit;
            ->stmt()
            ->fetchAll(\PDO::FETCH_ASSOC);

        #test
        #print_r($c); exit;

        foreach ($c as $k){
            $s = $k;
        }

        #test
        #print_r($s); exit;

        //查询并返回结果
        return $s['SUM(price)'] == 0 ? "0" : $s['SUM(price)'];
    }

    /**
     * 查询商品
     * @return array
     */
    function W_Item()
    {
        //查询并返回结果
        return $this->link->getAll("xrk_inventory", array('type','i_name'));
    }

    /**
     * 查询店铺
     * @return array
     */

    function W_Shops()
    {
        //查询并返回结果
        return $this->link->getAll("xrk_shops",'*');
    }

    /**
     * 查询企业客户名字
     * @return array
     */
    function G_Name()
    {
        //查询并返回结果
        return $this->link->getAll("xrk_ec", 'name');
    }

    /**
     * 查询每月指标
     * @return array
     */
    function M_Target($data)
    {

        //查询数据
        $s = $this->link->get("xrk_target", 'target',$data);

        //返回结果
        return $s['target'];
    }

    /**
     * 查询所有员工名字
     * @return array
     */
    function W_User_List()
    {
        return $this->link->getAll('admin','id,name,uname',array('t' => 1));
    }

    /**
     * 更新流水状态
     * @return array
     */
    function W_Set($data)
    {
        //设置交易方式
        $m = $data['mprice'] == "未付" ? "未付(已结款)" : "现金";

        switch($data['start']){

            case 'wf_ok':

                $this->link->update($this->tables, array(
                    'start' => 1,
                    'time'  => date('Y-m-d H:i:s'),
                    'mtime'  => $data['mtime'],
                    'mprice' => $m
                ), array('id' => $data['id']));

                return "未付款入账成功！";

                break;

            case 'ok':

                $this->link->update($this->tables, array(
                    'start' => 1,
                    'mtime'  => date('Y-m-d H:i:s'),
                    'mprice' => $m
                ), array('id' => $data['id']));

                return "入账成功！";

                break;

            case 'del':

                $this->link->update($this->tables, array(
                    'start' => 2,
                    'oname' => $_SESSION['uname']
                ), array('id' => $data['id']));

                $w = $this->link->get($this->tables,'item,num,addr',array('id' => $data['id']));

                switch($w['addr'])
                {
                    case "总仓库":
                        $addr = "warehouse";
                        break;

                    case "文化广场店":
                        $addr = "wh";
                        break;

                    case "白露店":
                        $addr = "bl";
                        break;
                }

                $I = $this->link->get($this->itables,array($addr,'type'),array('i_name' => $w['item']));

                if ($I['type'] == '服务费'){
                    return "退货成功!商品为服务费,不扣除库存!";
                }

                //计算要增加的库存数量
                $Num = $w['num'] + $I[$addr];


                $s = $this->link->update($this->itables,array($addr => $Num),array('i_name' => $w['item']));

                if ($s){
                    return '退货成功! 商品成功退回:'.$w['addr'].' 退货数量:'.$w['num'].' 现在库存为:'.$Num.' 原库存为:'.$I[$addr];
                }
                else{
                    return "databases update fail";
                }

                break;

            case 'up':

                //预留值，用于修改单据

                break;
        }
    }

    /**
     * 支出模块
     */

    function W_Expenditure()
    {

        //取本月时间
        $t = date('Y-m-');

        $query = $this->link->select('*')
            ->from($this->tables_Expenditure)
            ->where(array(
                'time like ? OR start != ? and start != ?',
                array('$t%',1,3)
            ))
            ->stmt()
            ->fetchAll(\PDO::FETCH_ASSOC);

        return $query;
    }

    /**
     * 添加支出项目
     */

    function W_Expenditure_Add($data)
    {

        //赋值，方便后面
        $time = $data['time'];
        $content = $data['text'];
        $money = $data['price'];
        $name = $data['name'];

        //空值检查
        if ($time == NULL || $content == NULL || $money == NULL || $name == NULL){
            return '表单没有填写完整';
        }
        else{
            return $this->link->add($this->tables_Expenditure,
                array(
                    //手动填写的数据
                    'itime' => $time,
                    'content' => $content,
                    'money' => $money,
                    'name' => $name,
                    //以下为默认值
                    'v1' => 0,
                    'v2' => 0,
                    'v3' => 0,
                    'start' => 0
                ));
        }
    }
    
    /**
     * 支出项目更改
     */
    function W_Expenditure_Set($data)
    {
        switch ($data['v']){
            case '1':
                //领导审批
                switch ($data['c']){
                    case '1': //通过
                        return $this->link->update($this->tables_Expenditure,array(
                            'v1' => 1,
                            'v1_name' => $_SESSION['uname'],
                            'v1_time' => date("Y-m-d H:i:s")
                        ) , array(
                            'id' => $data['id']
                        ));
                        break;
                    case '3': //拒绝
                        return $this->link->update($this->tables_Expenditure,array(
                            'v1' => 3,
                            'v1_name' => $_SESSION['uname'],
                            'v1_time' => date("Y-m-d H:i:s")
                        ) , array(
                            'id' => $data['id']
                        ));
                        break;
                    case '0': //取消
                        return $this->link->update($this->tables_Expenditure,array(
                            'v1' => 0,
                            'v1_name' => $_SESSION['uname'],
                            'v1_time' => date("Y-m-d H:i:s")
                        ) , array(
                            'id' => $data['id']
                        ));
                        break;
                }
                break;
            case '2':
                //财务上报出纳
                return $this->link->update($this->tables_Expenditure,array(
                    'v2' => 1,
                    'v2_name' => $_SESSION['uname'],
                    'v2_time' => date("Y-m-d H:i:s")
                ) , array(
                    'id' => $data['id']
                ));
                break;
            case '3':
                //出纳确认打款
                return $this->link->update($this->tables_Expenditure,array(
                    'v3' => 1,
                    'v3_name' => $_SESSION['uname'],
                    'v3_time' => date("Y-m-d H:i:s"),
                    'start' => 4
                ) , array(
                    'id' => $data['id']
                ));
                break;
            case '4':
                //申报人确认打款
                return $this->link->update($this->tables_Expenditure,array(
                    'o_time' => date("Y-m-d H:i:s"),
                    'start' => 1
                ) , array(
                    'id' => $data['id']
                ));
                break;
            case '5':
                //拒绝后删除按钮
                return $this->link->update($this->tables_Expenditure,array(
                    'o_time' => date("Y-m-d H:i:s"),
                    'start' => 3
                ) , array(
                    'id' => $data['id']
                ));
                break;
        }
    }

    //
}